package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//房间配置，房间钻石配置

//新增房间钻石配置
func NewRoomCard(data map[string]interface{}) (int64, error) {
	o := NewDBOrm(DBChessSysData)
	values, sql := InsertSql(TableRoomCardCfg, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//房间钻石列表
func ListRoomCard(gameId interface{}, multiOrm ...orm.Ormer) ([]orm.Params, error) {
	var allRc []orm.Params
	var err error
	Key := fmt.Sprintf("%v%v", KeyRoomCard, gameId)
	allRc, err = GetSliceCache(Key)
	if err != nil {
		return allRc, err
	}
	if allRc == nil {
		o := NewOrm(multiOrm, DBChessSysData)
		var rc []RoomCard
		sql := fmt.Sprintf(`
			SELECT
				card,round,idx,card_aa
			FROM
				%v
			WHERE
				game_id = ?
		`, TableRoomCardCfg)
		_, err := o.Raw(sql, gameId).QueryRows(&rc)
		if CheckError(err) {
			return allRc, err
		}
		for _, v := range rc {
			rcm := make(orm.Params)
			rcm["round"] = v.Round
			rcm["idx"] = v.Idx
			if v.Card != -1 {
				rcm["card"] = v.Card
			}
			if v.CardAa != -1 {
				rcm["card_aa"] = v.CardAa
			}
			allRc = append(allRc, rcm)
		}
		//即使为空也缓存，为了减少因为数据库里不存在此数据而步骤与数据库交互,所以是用checkError而不是checkNoExist
		SetSliceCache(Key, allRc, CacheExpire)
	}
	return allRc, nil
}

func RoomCardById(gameId int64, multiOrm ...orm.Ormer) ([]*RoomCard, error) {
	var rc []*RoomCard
	o := NewOrm(multiOrm, DBChessSysData)
	sql := fmt.Sprintf(`
			SELECT
				id,card,round,card_aa,idx
			FROM
				%v
			WHERE
				game_id = ?
		`, TableRoomCardCfg)
	_, err := o.Raw(sql, gameId).QueryRows(&rc)
	if CheckNoExist(err) {
		return rc, nil
	}
	return rc, err
}

//更新房间钻石
func UpdateRoomCard(rc map[string]interface{}, id int64) error {
	o := NewDBOrm(DBChessSysData)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableRoomCardCfg, rc, condition)
	_, err := o.Raw(sql, values).Exec()
	return err
}

//删除房间钻石
func DeleteRoomCard(id int64) (int64, error) {
	o := NewDBOrm(DBChessSysData)
	condition := fmt.Sprintf("id=%v", id)
	sql := DeleteSql(TableRoomCardCfg, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//根据游戏id删除房间钻石配置
func DeleteRoomCardByGameId(gameId int64) (int64, error) {
	o := NewDBOrm(DBChessSysData)
	condition := fmt.Sprintf("game_id=%v", gameId)
	sql := DeleteSql(TableRoomCardCfg, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//房间列表
func ListTable(p ListParams, tableId, hostId, clubId, isClose int64, clubName, passwd string) ([]orm.Params, int64, error) {
	where := " 1=1 "
	if tableId != 0 {
		where = where + fmt.Sprintf(" AND r.tableid = %v", tableId)
	}
	if passwd != "" {
		where = where + fmt.Sprintf(" AND r.passwd = %v", passwd)
	}

	if hostId != 0 {
		where = where + fmt.Sprintf(" AND r.hostid = %v", hostId)
	}
	if clubId != 0 {
		where = where + fmt.Sprintf(" AND r.clubid = %v", clubId)
	}
	if clubName != "" {
		where = where + fmt.Sprintf(" AND c.name LIKE '%v'", "%"+clubName+"%")
	}
	if isClose != -1 {
		where = where + fmt.Sprintf(" AND r.isclose = %v", isClose)
	}

	limit := (p.PageIndex - 1) * p.PageSize
	o := NewDBOrm(DBChess)
	sql := fmt.Sprintf(`
			SELECT
				r.*,c.name AS club_name,c.password AS club_password,u.nickname AS host_name
			FROM
				%v AS r
			LEFT JOIN
				%v AS c
			ON r.clubid = c.id
			LEFT JOIN
				%v AS u
			ON r.hostid= u.uid
			WHERE
				%v
			ORDER BY tableid DESC
			LIMIT ?,?
		`, TableRoom, TableClub, TableClientUser, where)
	var rc []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&rc)
	if CheckError(err) {
		return rc, 0, err
	}
	for _, v := range rc {
		v["game_id"] = GenGameId(v["gametype"], v["playtype"])
	}
	sql = fmt.Sprintf(`
			SELECT
				COUNT(1)
			FROM
				%v AS r
			LEFT JOIN
				%v AS c
			ON r.clubid = c.id
			LEFT JOIN
				%v AS u
			ON r.hostid = u.uid
			WHERE
				%v
			`, TableRoom, TableClub, TableClientUser, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return rc, count, err
	}
	return rc, count, nil
}

func TableInfoById(tableId int64) (*Table, error) {
	sql := fmt.Sprintf(`
		SELECT
			gametype,playtype
		FROM
			%v
		WHERE
			tableid = ?
		LIMIT 1
		`, TableRoom)
	o := NewDBOrm(DBChess)
	var table Table
	err := o.Raw(sql, tableId).QueryRow(&table)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &table, err
}
